package com.easy.utils;


import com.easy.config.log.MyLog;
import com.easy.threads.actuator.Job;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;

/**
 * 描述: 线程管理
 * 1、等待线程、运行线程，临时线程 （以分区分组）
 *
 * @author gwj
 * @date 2024年01月05日 14:51
 */

public class JobPoolManage implements java.io.Serializable {


    private static final long serialVersionUID = 561603730681515041L;


    /**
     * 等待线程，可执行线程
     */
    private static final Map<String, List<Job>> WAIT_JOB_PARTITION = new ConcurrentHashMap<>();


    public static List<Job> getWaitJobList(String partitionKey) {
        return WAIT_JOB_PARTITION.get(partitionKey);
    }

    public static Job getWaitJob(String partitionKey) {
        List<Job> jobs = WAIT_JOB_PARTITION.get(partitionKey);

        return jobs.isEmpty() ? null : jobs.remove(0);
    }

    public static void addWaitJob(final String partitionKey, Job waitJob) {
        synchronized (partitionKey) {
            List<Job> jobs = WAIT_JOB_PARTITION.get(partitionKey);
            if (jobs == null) {
                List<Job> waitJobList = new CopyOnWriteArrayList<>();
                waitJobList.add(waitJob);
                WAIT_JOB_PARTITION.put(partitionKey, waitJobList);
                return;
            }
            jobs.add(waitJob);
        }
        MyLog.getLogger().log(Level.INFO, "{}分区,添加线程【{}】,线程状态：{},JOB状态：{},添加成功", new Object[]{partitionKey, waitJob.getName(), waitJob.getState(), waitJob.getJobStatus()});
    }
}
